from urllib.parse import quote

import requests

API_KEY = "ft74jJTTTkqoLGp4E6IeUO80"
SECRET_KEY = "jjA6WKbYtHnFObE17kGYvDvZZCer25m3"


class IDCardService:
    def main(self, urllist):
        access_token = self.get_access_token()
        if not access_token:
            return {"error": "Failed to get access token"}

        # 对urllist进行URL编码
        encoded_urllist = quote(urllist, safe=':/?=&%')

        url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={access_token}"
        payload = f'id_card_side=front&url={encoded_urllist}&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.post(url, headers=headers, data=payload)
        return response.json()

    def get_access_token(self):
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
        response = requests.post(url, params=params)
        if response.status_code == 200:
            return response.json().get("access_token")
        else:
            return None


idc = IDCardService()
